﻿using GalaSoft.MvvmLight.Command;
using KJSync.Access.Models;
using KJSyncXP.Access.Context;
using KJSyncXP.Extensions;
using KJSyncXP.Sqlite.Model;
using KJSyncXP.SQLite.Context;
using LiveCharts;
using LiveCharts.Wpf;
using log4net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace KJSyncXP.ViewModels
{
    // 【新增】数据行包装类：用于添加“是否选中”状态
    public class CheckResultItem : INotifyPropertyChanged
    {
        public SqliteDat200Rh Data { get; set; }

        private bool _isSelected;
        public bool IsSelected
        {
            get => _isSelected;
            set
            {
                _isSelected = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsSelected)));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

    public class CheckResultViewModel : BaseViewModel
    {
        private readonly ILog _logger;
        private readonly AppConfig _appConfig;
        private readonly SqliteDbContext _sqliteCtx;

        public RelayCommand QueryCheeckResultCommand { get; private set; }

        // 查询条件
        private string _batchNo;
        public string BatchNo
        {
            get => _batchNo;
            set { _batchNo = value; RaisePropertyChanged("BatchNo"); }
        }

        private DateTime? _startDate;
        public DateTime? StartDate
        {
            get => _startDate;
            set { _startDate = value; RaisePropertyChanged("StartDate"); }
        }

        private DateTime? _endDate;
        public DateTime? EndDate
        {
            get => _endDate;
            set { _endDate = value; RaisePropertyChanged("EndDate"); }
        }

        // 【改造】查询结果：包装为带“是否选中”的项
        private List<CheckResultItem> _checkResults;
        public List<CheckResultItem> CheckResults
        {
            get => _checkResults;
            set
            {
                _checkResults = value;
                RaisePropertyChanged("CheckResults");
                // 订阅“选中状态变化”事件，触发图表刷新
                if (value != null)
                {
                    foreach (var item in value)
                    {
                        item.PropertyChanged += (s, e) =>
                        {
                            if (e.PropertyName == nameof(CheckResultItem.IsSelected))
                            {
                                LoadSelectedCharts();
                            }
                        };
                    }
                }
            }
        }

        // LiveCharts：图表系列（多组折线）
        private SeriesCollection _chartSeries;
        public SeriesCollection ChartSeries
        {
            get => _chartSeries;
            set { _chartSeries = value; RaisePropertyChanged("ChartSeries"); }
        }

        // LiveCharts：X轴标签
        private List<string> _chartLabels;
        public List<string> ChartLabels
        {
            get => _chartLabels;
            set { _chartLabels = value; RaisePropertyChanged("ChartLabels"); }
        }

        // 曲线类型集合（硫化曲线、上模温度、下模温度）
        private List<string> _curveTypes = new List<string> { "硫化曲线", "上模温度曲线", "下模温度曲线" };
        public List<string> CurveTypes
        {
            get => _curveTypes;
            set { _curveTypes = value; RaisePropertyChanged("CurveTypes"); }
        }

        // 选中的曲线类型
        private string _selectedCurveType;
        public string SelectedCurveType
        {
            get => _selectedCurveType;
            set
            {
                _selectedCurveType = value;
                RaisePropertyChanged("SelectedCurveType");
                LoadSelectedCharts(); // 切换类型时刷新图表
            }
        }

        public CheckResultViewModel(ILog log, AppConfig appConfig, SqliteDbContext sqliteCtx)
        {
            _logger = log;
            _appConfig = appConfig;
            _sqliteCtx = sqliteCtx;
            QueryCheeckResultCommand = new RelayCommand(QueryCheeckResult);
            SelectedCurveType = "硫化曲线"; // 默认选中“硫化曲线”
        }

        // 查询数据并包装为带选择状态的项
        public void QueryCheeckResult()
        {
            // 基础查询（根据实际表名调整）
            var query = _sqliteCtx.Db.Queryable<SqliteDat200Rh>();

            // 拼接查询条件
            if (!string.IsNullOrEmpty(BatchNo))
            {
                query = query.Where(r => r.F14.Contains(BatchNo));
            }
            if (StartDate.HasValue)
            {
                var start = StartDate.Value.Date;
                query = query.Where(r => r.CREATE_DATE >= start);
            }
            if (EndDate.HasValue)
            {
                var end = EndDate.Value.Date.AddDays(1).AddTicks(-1);
                query = query.Where(r => r.CREATE_DATE <= end);
            }

            // 执行查询 + 包装为带“是否选中”的项
            var sqliteResults = query.ToList();
            CheckResults = sqliteResults.Select(r => new CheckResultItem { Data = r, IsSelected = false }).ToList();
        }

        // 【新增】加载所有选中行的图表
        public void LoadSelectedCharts()
        {
            try
            {
                // 获取所有选中的数据行
                var selectedItems = CheckResults?.Where(item => item.IsSelected).Select(item => item.Data).ToList();
                if (selectedItems == null || !selectedItems.Any())
                {
                    ChartSeries = new SeriesCollection();
                    ChartLabels = new List<string>();
                    return;
                }

                List<string> combinedLabels = new List<string>();
                SeriesCollection series = new SeriesCollection();

                // 遍历每个选中的行，生成对应曲线
                foreach (var data in selectedItems)
                {
                    // 解析X轴标签（从DatVal_1字段拆分）
                    var labels = string.IsNullOrEmpty(data.DatVal_1)
                        ? new List<string>()
                        : data.DatVal_1.Split('/').ToList();
                    // 合并X轴标签（取第一个有标签的行的标签）
                    if (!combinedLabels.Any() && labels.Any())
                        combinedLabels = labels;

                    // 根据“选中的曲线类型”，解析对应数值字段
                    List<double> values = new List<double>();
                    switch (SelectedCurveType)
                    {
                        case "硫化曲线":
                            values = ParseDoubleList(data.DatVal_2);
                            break;
                        case "上模温度曲线":
                            values = ParseDoubleList(data.DatVal_7);
                            break;
                        case "下模温度曲线":
                            values = ParseDoubleList(data.DatVal_8);
                            break;
                    }

                    // 生成折线系列（标题用“胶号+车次”标识）
                    string seriesTitle = $"{data.F10}({data.F15})";
                    series.Add(new LineSeries
                    {
                        Title = seriesTitle,
                        Values = new ChartValues<double>(values)
                    });
                }

                ChartLabels = combinedLabels;
                ChartSeries = series;
            }
            catch (Exception ex)
            {
                _logger.Error("加载选中图表数据失败", ex);
                ChartSeries = new SeriesCollection();
                ChartLabels = new List<string>();
            }
        }

        // 辅助方法：将“/”分隔的字符串转为double列表
        private List<double> ParseDoubleList(string csvString)
        {
            if (string.IsNullOrEmpty(csvString))
                return new List<double>();

            return csvString.Split('/')
                .Select(s =>
                {
                    if (double.TryParse(s, out double result))
                        return result;
                    return 0d; // 解析失败时默认值为0
                })
                .ToList();
        }
    }
}